package com.youkeda.yunmusic.web.control;

import com.youkeda.yunmusic.web.model.Comment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class CommentPostControl {

    private static Map<String, List<Comment>>comments = new HashMap<>();
    private static List<Comment> res;

    @RequestMapping(value="comment/post")
    public String post(//@RequestParam(value="songId") String songId,
                       Comment comment){
        String songId = "35847388";
        Date commentTime = new Date();
        comment.setCommentTime(commentTime);
        //xxx-xxx-xxx-xxx
        comment.setId(UUID.randomUUID().toString());
        //comments.remove(0);
//        if(comments.containsKey(songId)){
//            res = comments.get(songId);
//        }else{
//            res = new ArrayList<>();
//            //就是第一次comments不存在key为songId的这个数据，
//            //通过new一个ArrayList，并将songId和这个new出来的res绑在一起
//            comments.put(songId,res);
//        }
//        res.add(comment);
        // 评论数据的添加
        comments.computeIfAbsent(songId,v->new ArrayList<>()).add(comment);

        List<Comment> commentList = comments.get(songId);

        //第一个参数是集合，第二个参数是比较函数
        //java 的对象实例是会传递的，所以虽然没有直接修改集合，但是集合里的对象发生变化，集合也会生效的
//        Collections.sort(commentList, new Comparator<Comment>() {
//            @Override
//            public int compare(Comment o1, Comment o2) {
//                if(o1.getCommentTime().after(o2.getCommentTime())){
//                    return -1;
//                }else{
//                    return 1;
//                }
//            }
//        });
        sort(commentList);

        return "redirect:/comments?songId="+songId;
    }

    public List<Comment> getComments(String songId){
        return comments.get(songId);
    }


    private void sort(List<Comment> commentList){
        int m, n;
        for(m=0;m<commentList.size()-1;m++){
            for(n=m;n<commentList.size();n++){
                if(commentList.get(m).getCommentTime().
                        before(commentList.get(n).getCommentTime())){
                    Comment temp;
                    temp = commentList.get(n);
                    commentList.set(n,commentList.get(m));
                    commentList.set(m,temp);
                }
            }
        }
    }

}
